package com.elinkway.infinitemovies.utils;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.bean.LocationData;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.LocationParser;
import com.elinkway.infinitemovies.listener.MyTencentLocationListener;
import com.lvideo.http.bean.LVideoDataHull;

import java.util.Timer;
import java.util.TimerTask;

import static com.tencent.qqlive.mediaplayer.config.TencentVideo.getApplicationContext;

/**
 * 定位管理类，使用的是腾讯地图SDK，获取实时经纬度
 *
 * @author daipei
 */
public class MyLocationManager implements AMapLocationListener {
    private boolean isIgnore = false;//打指定城市包才置为true
    private static int TIMEOUT = 3000;
    // zhengzhou 经纬度
    private static String LONGITUDE = "113.627427";
    private static String LATITUDE = "34.762756";
    // 热门旅游城市 经纬度 重庆（106.552566,29.556923）
//    private static String LONGITUDE = "106.552566";
//    private static String LATITUDE = "29.556923";

    public static final String TAG = "MyLocationManager";
    private Context mContext;

    private MyTencentLocationListener mListener;
    private Timer mTimer;
    private TimerTask mTimerTask;
    /**
     * 定位是否成功
     */
    public static String IS_LOCATION_SUCCESS = "isLocationSuccess";
    /**
     * 定位成功时间戳
     */
    public static String LOCATION_SUCCESS_TIME = "locationSuccessTime";
    /**
     * 定位成功城市
     */
    public static String LOCATION_CITY = "locationCity";
    public static String LOCATION_CITY_CODE = "locationCityCode";
    /**
     * 存储地理信息的key
     */
    public static String LOCATIONKEY = "locationKey";

    public static String HAS_FIXED_LOCATION = "has_fixed_location";     //用于修改城市码
    /**
     * 存储经度
     */
    public static String LOCATIONLONGITUDE = "longitude";
    /**
     * 存储纬度
     */
    public static String LOCATIONLATITUDE = "latitude";

    private RequestLocationDataTask mLocationDataTask;
    private int status = -1;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption mLocationOption;
    private AMapLocation mLocation;

    public MyLocationManager(Context context, MyTencentLocationListener listener) {
        mContext = context;
        mListener = listener;
        startTimer();
//        mLocationManager = TencentLocationManager.getInstance(context);
//        status = mLocationManager.requestLocationUpdates(TencentLocationRequest.create()
//                .setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_GEO)
//                .setInterval(10).setAllowDirection(true), this);
//        LogUtils.e(TAG, "location register status is " + status);
        //初始化定位
        initLocation();
    }

    private void initLocation() {
        mLocationOption = new AMapLocationClientOption();
        // 设置定位模式Hight_Accuracy为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode (AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress (true);
        // 设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation (false);
        // 设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan (true);
        // 设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable (true);
        // 设置定位间隔,单位毫秒,默认为2000ms;这里设置为30分钟定位一次
        mLocationOption.setInterval (1000 * 60 * 30 );

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationOption(mLocationOption);
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //启动定位
        mLocationClient.startLocation();
    }

    public static String getDefaultLOCATIONKEY() {
        return LONGITUDE;
    }

    public static String getDefaultLATITUDE() {
        return LATITUDE;
    }

    /**
     * 开始计时器，3秒钟超时()
     */
    private void startTimer() {
        LogUtils.e("MyLocationManager", "startTimer");
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                ((Activity) mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 这段代码只会在 mLocationDataTask没有执行完才执行
                        if (null != mLocationDataTask
                                && !mLocationDataTask.isCancelled()) {
                            LogUtils.e(TAG, "mLocationDataTask is not null");
                            mLocationDataTask.cancel();
                            LogUtils.e(TAG, "mLocationDataTask cancle");
                            mLocationDataTask = null;
                        }
                        LogUtils.e(TAG, "!!!!时间到了!!!!");
                        mLocationDataTask = new RequestLocationDataTask(MoviesApplication.getInstance(), "", "");
                        mLocationDataTask.start();
                    }
                });
            }
        };
        mTimer.schedule(mTimerTask, TIMEOUT);
    }

    /**
     * 清空监听的每条消息的发送时间处理消息超时 这里关闭掉Timer 与 TimerTask
     */
    private void cleanSendTimerTask() {
        if (mTimerTask != null) {
            mTimerTask.cancel();
            LogUtils.e(TAG, "mTimerTask cancle");
            mTimerTask = null;
        }
        if (mTimer != null) {
            mTimer.cancel();
            mTimer.purge();
            LogUtils.e(TAG, "mTimer cancle");
            mTimer = null;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation location) {
        if (location != null) {
            if (location.getErrorCode() == 0) {
                mLocation=location;
                //解析定位结果
                SharePreferenceManager.saveVaule(mContext, IS_LOCATION_SUCCESS,
                        true);
                SharePreferenceManager.saveVaule(mContext, LOCATION_SUCCESS_TIME, String.valueOf(location.getTime()));
                SharePreferenceManager.saveVaule(mContext, LOCATION_CITY,location.getCity());
                SharePreferenceManager.saveVaule(mContext, LOCATION_CITY_CODE,location.getCityCode());
                String latitude = String.valueOf(location.getLatitude());
                String longitude = String.valueOf(location.getLongitude());
                if (isIgnore) {
                    mLocationDataTask = new RequestLocationDataTask(MoviesApplication.getInstance(),
                            LONGITUDE, LATITUDE);
                    LogUtils.e(TAG, "!!!!!!!!!!!default zhengzhou!!!!!!!!!!! longitude is " + LONGITUDE + " and latitude is " + LATITUDE);

                    SharePreferenceManager.saveVaule(mContext, LOCATIONLONGITUDE,
                            LONGITUDE);

                    SharePreferenceManager.saveVaule(mContext, LOCATIONLATITUDE,
                            LATITUDE);
                } else {
                    mLocationDataTask = new RequestLocationDataTask(MoviesApplication.getInstance(),
                            longitude, latitude);
                    LogUtils.e(TAG, "!!!!!!!!!!!location!!!!!!!!!!! longitude is " + longitude + " and latitude is " + latitude);
                    SharePreferenceManager.saveVaule(mContext, LOCATIONLONGITUDE,
                            longitude);

                    SharePreferenceManager.saveVaule(mContext, LOCATIONLATITUDE,
                            latitude);
                }
                mLocationDataTask.start();
//                mLocationManager.removeUpdates(this);
                mLocationClient.stopLocation();


            }else {
                SharePreferenceManager.saveVaule(mContext, IS_LOCATION_SUCCESS,
                        false);
                LogUtils.e(TAG, "onLocationChanged failed");
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError","location Error, ErrCode:"
                        + location.getErrorCode() + ", errInfo:"
                        + location.getErrorInfo());
            }
        }

    }


    /**
     * 停止定位
     */
    public void stopLocation() {
//        mLocationManager.removeUpdates(this);
        mLocationClient.stopLocation();
        cleanSendTimerTask();
    }


    /**
     * 地域策略，请求
     *
     * @author daipei
     */
    private class RequestLocationDataTask extends
            MoviesHttpAsyncTask<LocationData> {
        private String mLongitude;// 经度
        private String mLatitude;// 纬度

        public RequestLocationDataTask(Context context, String longitude,
                                       String latitude) {
            super(context);
            mLongitude = longitude;
            mLatitude = latitude;

        }

        @Override
        public void netNull() {
            super.netNull();
            LogUtils.e(TAG, "!!!!netNull 请求出错!!!!");
            if(Utils.isSimulator()){
                SharePreferenceManager.saveVaule(mContext, LOCATIONKEY, "CN_1_5_1");
            }
            mListener.onLocationTimeOut();
            stopLocation();
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
            LogUtils.e(TAG, "!!!!netErr 请求出错!!!!");
            if(Utils.isSimulator()){
                SharePreferenceManager.saveVaule(mContext, LOCATIONKEY, "CN_1_5_1");
            }
            mListener.onLocationTimeOut();
            stopLocation();
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
            LogUtils.e(TAG, "!!!!dataNull 请求出错!!!!");
            if(Utils.isSimulator()){
                SharePreferenceManager.saveVaule(mContext, LOCATIONKEY, "CN_1_5_1");
            }
            mListener.onLocationTimeOut();
            stopLocation();
        }

        @Override
        public LVideoDataHull<LocationData> doInBackground() {
            LocationParser locationParser = new LocationParser();
            String location = mLatitude + "," + mLongitude;
            SharePreferenceManager.saveVaule(mContext, SharePreferenceManager.LOCATION_LAT_LON, location);
            String province = mLocation.getProvince();
            String city = mLocation.getCity();
            String county = mLocation.getDistrict();

//                return MoviesHttpApi.requestLocationData(locationParser,location);
            return MoviesHttpApi.requestCityInfo(locationParser, mLatitude, mLongitude, province, city, county);

        }

        @Override
        public void onPostExecute(int updateId, LocationData result) {
            if(Utils.isSimulator()){
                SharePreferenceManager.saveVaule(mContext, LOCATIONKEY, "CN_1_5_1");
            }else{
                if(!"1".equals(SharePreferenceManager.getVaule(mContext, HAS_FIXED_LOCATION, "0"))){
                    SharePreferenceManager.saveVaule(mContext, LOCATIONKEY,
                            result.getCityinfo());
                }
            }
            mListener.onLocationSuccese(result.getCityinfo());
            stopLocation();
        }
    }
}
